package com.stylefeng.guns.rest.modular.wz.service.impl;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.core.support.HttpKit;
import com.stylefeng.guns.rest.common.constant.Consts;
import com.stylefeng.guns.rest.common.exception.BizExceptionEnum;
import com.stylefeng.guns.rest.common.exception.ParamException;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.common.util.StringUtils;
import com.stylefeng.guns.rest.config.properties.JwtProperties;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.EnWz;
import com.stylefeng.guns.rest.enums.EnWzAdv;
import com.stylefeng.guns.rest.enums.EnWzUser;
import com.stylefeng.guns.rest.enums.EnWzUserFinanceRecord;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.dao.WzAdvDao;
import com.stylefeng.guns.rest.modular.wz.service.IWzAdvService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 广告表 服务实现类
 * </p>
 *
 * @author ruiyifeng123
 * @since 2018-03-20
 */
@Service
public class WzAdvServiceImpl extends ServiceImpl<WzAdvMapper, WzAdv> implements IWzAdvService {

    @Autowired
    private WzAdvMapper advMapper;
    @Autowired
    private WzUserInfoMapper userInfoMapper;
    @Autowired
    private WzCouponMapper couponMapper;
    @Autowired
    private WzQuestionMapper questionMapper;
    @Autowired
    private WzAnswerMapper answerMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WzUserAdvRecordMapper userAdvRecordMapper;
    @Autowired
    private WzUserAdvCollectionMapper userAdvCollectionMapper;
    @Autowired
    private WzAdvUserMapper advUserMapper;
    @Autowired
    private WzUserQuestionnaireMapper userQuestionnaireMapper;
    @Autowired
    private WzUserMapper userMapper;
    @Autowired
    private WzAdvDao advDao;
    @Autowired
    private WzUserCouponMapper userCouponMapper;
    @Autowired
    private WzNewsMapper newsMapper;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private WzUserQuestionnaireServiceImpl userQuestionnaireService;
    @Autowired
    private WzAnswerServiceImpl answerService;
    @Autowired
    private WzUserFinanceRecordMapper userFinanceRecordMapper;
    @Autowired
    private WzQuestionnaireMapper questionnaireMapper;
    @Autowired
    private WzUserAdvMapper userAdvMapper;
    @Autowired
    private WzAdvShareMapper advShareMapper;
    @Autowired
    private WzRedpacketCommentMapper redpacketCommentMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private WzShareMapper shareMapper;
    @Autowired
    private PfOpenCityMapper openCityMapper;


    public ParamMap advParamMap(ParamMap paramMap) {
        paramMap.put("contant","");
        Map userInfoMap = new HashMap();
        userInfoMap.put("merchantTel","");
        userInfoMap.put("merchantAddress","");
        userInfoMap.put("merchantEmail","");
        userInfoMap.put("merchantWebsite","");
        userInfoMap.put("merchantLongitude","");
        userInfoMap.put("merchantLatitude","");
        userInfoMap.put("merchantName","");
        paramMap.put("contant",userInfoMap);
        List list = new ArrayList();
        paramMap.put("couponList",list);
        paramMap.put("advQuestionnaire",list);
        paramMap.put("advQuestionnaireId", "");
        paramMap.put("hasCollection",0);
        paramMap.put("advQuestionId","");
        paramMap.put("screenQuestionnaireId","");
        paramMap.put("screenQuestionnaireList",list);
        return paramMap;
    }

    /**
     * 新广告详情
     */
//    public Res advDetails(ParamMap paramMap) {
//        String iosVersion = paramMap.getStr("iosVersion");//iosVersion
//        String advId = paramMap.getStr("advId");//广告id
//        int type = paramMap.getInt("type");//广告详情类型
//        String advUserId = paramMap.getStrValid("advUserId");//广告问卷id
//        //广告缓存
//        List<Map<String,Object>>  list = cacheService.adv(Long.parseLong(advId));
//        String userCodes = paramMap.getStr("userCode");
//        Long userCode = null;
//        if(StringUtils.isBlankStr(userCodes)){
//            userCode = jwtTokenUtil.getUserCodeFromToken();
//        }else{
//            userCode = Long.parseLong(userCodes);
//        }
//        paramMap.clear();
//        paramMap.put("advId",advId);
//        paramMap.put("advUserId",advUserId);
//        paramMap = advParamMap(paramMap);
//        //查询商户联系方式
//        if((Long) list.get(0).get("userInfoId") != null){
//            //缓存商户联系方式
//            List<Map<String,Object>> userInfoList = cacheService.userInfo((Long)list.get(0).get("userInfoId"));
//            if(userInfoList.size() > 0){
//                paramMap.put("contant",userInfoList.get(0));
//            }
//        }
//        //广告提问
//        if(type == EnWzAdv.DETAIL_TYPE_INDEX.getIndex()){
//            paramMap.put("advQuestionId",list.get(0).get("advQuestionId"));
//        }
//        //是否收藏
//        int c = userAdvCollectionMapper.selectCount(new EntityWrapper<WzUserAdvCollection>().eq("user_code",userCode).eq("adv_id",Long.parseLong(advId)).eq("adv_user_id",advUserId));
//        if(c > 0){
//            paramMap.put("hasCollection",1);
//        }
//        paramMap.put("coverUrl",list.get(0).get("coverUrl"));
//        //筛选问题
//        if(!StringUtils.isBlankStr(list.get(0).get("screenQuestionnaireId").toString())){
//            WzQuestionnaire questionnaire = questionnaireMapper.selectById(Long.parseLong(list.get(0).get("screenQuestionnaireId").toString()));
//            List questionList = new ArrayList();
//            List<WzQuestion> questions = questionMapper.selectList(new EntityWrapper<WzQuestion>().eq("questionnaire_id",questionnaire.getQuestionnaireId()).orderBy("sort",true));
//            for(WzQuestion q:questions){
//                Map map = new HashMap();
//                List<Map<String,Object>>  answerList = answerMapper.selectMaps(new EntityWrapper<WzAnswer>().eq("question_id",q.getQuestionId()));
//                for(Map<String, Object> map1:answerList){
//                    int cc = userQuestionnaireMapper.selectCount(new EntityWrapper<WzUserQuestionnaire>().eq("user_code",userCode.toString()).eq("answer_id",map1.get("answerId")));
//                    if(cc > 0){
//                        map1.put("selected","1");
//                    }else{
//                        map1.put("selected","0");
//                    }
//                }
//                map.put("answerList",answerList);
//                map.put("question",q.getQuestion());
//                map.put("questionType",q.getQuestionType());
//                map.put("questionId",q.getQuestionId());
//                map.put("isStatistics",q.getIsStatistics());
//                map.put("sort",q.getSort());
//                questionList.add(map);
//            }
//            paramMap.put("screenQuestionnaireList",questionList);
//            paramMap.put("screenQuestionnaireId", list.get(0).get("screenQuestionnaireId"));
//        }
//        paramMap.put("title",list.get(0).get("title"));
//        paramMap.put("coverUrl",list.get(0).get("coverUrl"));
//        paramMap.put("advDetail",list.get(0).get("advDetail"));
//        if(StringUtils.isNotBlank(list.get(0).get("shareLink").toString())){
//            paramMap.put("shareLink","http://share.50waizhuan.com/"+list.get(0).get("advId")+".html");
//        }
//        paramMap.put("shareReward",list.get(0).get("shareReward"));
//        paramMap.put("avatarUrl",list.get(0).get("avatarUrl"));
//        paramMap.put("nickName",list.get(0).get("nickName"));
//        if(list.get(0).get("shareReward").toString().equals("0")){
//            paramMap.put("rewardShareLink", "");
//            paramMap.put("isShare", 0);
//            paramMap.put("shareNumber",0);//参与分享人数
//        }else{
//            List<WzAdvShare> advShares = advShareMapper.selectList(new EntityWrapper<WzAdvShare>().eq("adv_id",advId));
//            paramMap.put("shareNumber",advShares.size());//参与分享人数
//            int count = advShareMapper.selectCount(new EntityWrapper<WzAdvShare>().eq("adv_id",Long.parseLong(advId)).eq("user_code",userCode));
//            if(count > 0){
//                paramMap.put("isShare", 1);
//            }else{
//                paramMap.put("isShare", 0);
//            }
//            if(Consts.dev.equals("true")){
//                paramMap.put("rewardShareLink", "http://50wz.viphk1.ngrok.org/wz/wzShare/share?advId="+advId+"&type=1&userCode="+userCode.toString()+"");
//            }else{
//                paramMap.put("rewardShareLink", ""+Consts.Adv_Share_Api_Domain+"/wz/wzShare/share?advId="+advId+"&type=1&userCode="+userCode.toString()+"");
//            }
//        }
//        int commentNumber = redpacketCommentMapper.selectCount(new EntityWrapper<WzRedpacketComment>().eq("adv_id",Long.parseLong(advId)));
//        paramMap.put("commentNumber",commentNumber);
//        paramMap.put("userCode",list.get(0).get("userCode"));
//        paramMap.put("status",list.get(0).get("status"));
//        if(StringUtils.isNotBlank(list.get(0).get("shareDesc").toString())){
//            paramMap.put("shareDesc", list.get(0).get("shareDesc").toString());
//        }else{
//            paramMap.put("shareDesc", Consts.shareDesc);
//        }
//        return Res.success(paramMap);
//    }

    /**
     * 广告详情
     */
    public Res advDetail(ParamMap paramMap) {
        String advId = paramMap.getStr("advId");//广告id
        //广告缓存
        List<Map<String,Object>>  list = cacheService.adv(Long.parseLong(advId));
        String userCodes = paramMap.getStr("userCode");
        Long userCode = null;
        if(StringUtils.isBlankStr(userCodes)){
            userCode = jwtTokenUtil.getUserCodeFromToken();
        }else{
            userCode = Long.parseLong(userCodes);
        }
        paramMap.clear();
        paramMap.put("advId",advId);
//        paramMap.put("advUserId",advUserId);
        paramMap = advParamMap(paramMap);
        paramMap.put("coverUrl",list.get(0).get("coverUrl"));
        paramMap.put("title",list.get(0).get("title"));
        if(list.get(0).get("subtype").toString().equals("50")){
            paramMap.put("title",list.get(0).get("subtitle"));
        }
        paramMap.put("coverUrl",list.get(0).get("coverUrl"));
        paramMap.put("advDetail",list.get(0).get("advDetail"));
        paramMap.put("shareLink",list.get(0).get("shareLink"));
        paramMap.put("shareReward",list.get(0).get("shareReward"));
        paramMap.put("avatarUrl",list.get(0).get("avatarUrl"));
        paramMap.put("nickName",list.get(0).get("nickName"));
        paramMap.put("subtype",list.get(0).get("subtype"));
        if(list.get(0).get("shareReward").toString().equals("0")){
            paramMap.put("rewardShareLink", "");
            paramMap.put("isShare", 0);
            paramMap.put("shareNumber",0);//参与分享人数
        }else{
            List<WzAdvShare> advShares = advShareMapper.selectList(new EntityWrapper<WzAdvShare>().eq("adv_id",advId));
            paramMap.put("shareNumber",advShares.size());//参与分享人数
            int count = advShareMapper.selectCount(new EntityWrapper<WzAdvShare>().eq("adv_id",Long.parseLong(advId)).eq("user_code",userCode));
            if(count > 0){
                paramMap.put("isShare", 1);
            }else{
                paramMap.put("isShare", 0);
            }
            if(Consts.dev.equals("true")){
                paramMap.put("rewardShareLink", ""+Consts.Adv_Share_Api_Domain_Test+"/wz/wzShare/share?advId="+advId+"&type=1&userCode="+userCode.toString()+"");
            }else{
                paramMap.put("rewardShareLink", ""+Consts.Adv_Share_Api_Domain+"/wz/wzShare/share?advId="+advId+"&type=1&userCode="+userCode.toString()+"");
            }
        }
        int commentNumber = redpacketCommentMapper.selectCount(new EntityWrapper<WzRedpacketComment>().eq("adv_id",Long.parseLong(advId)));
        paramMap.put("commentNumber",commentNumber);
        paramMap.put("userCode",list.get(0).get("userCode"));
        paramMap.put("status",list.get(0).get("status"));
        if(StringUtils.isNotBlank(list.get(0).get("shareDesc").toString())){
            paramMap.put("shareDesc", list.get(0).get("shareDesc").toString());
        }else{
            paramMap.put("shareDesc", Consts.shareDesc);
        }
        return Res.success(paramMap);
    }

    /**
     * 收藏、喜欢新闻
     */
//    @Transactional
//    public Res newsCollection(ParamMap p, Long userCode,int type) {
//        int c = userAdvCollectionMapper.selectCount(new EntityWrapper<WzUserAdvCollection>().eq("user_code",userCode).eq("adv_id",p.getStr("advId")).eq("type",type));
//        if(c > 0 && type == EnWzUser.USER_ADV_Collection.getIndex()){
//            return Res.fail("已经收藏!");
//        }else if(c > 0 && type == EnWzUser.USER_ADV_Like.getIndex()){
//            return Res.fail("已经喜欢!");
//        }
//        WzNews news = newsMapper.selectById(p.getLong("advId"));
//        WzUserAdvCollection userAdvCollection = new WzUserAdvCollection();
//        userAdvCollection.setAdvId(p.getLong("advId"));
//        userAdvCollection.setCreateTime(new Date());
//        userAdvCollection.setUserCode(userCode);
//        userAdvCollection.setCoverUrl(news.getCoverUrl());
//        userAdvCollection.setType(type);
//        userAdvCollection.setTitle(news.getTitle());
//        userAdvCollection.setHasDetail(news.getHasDetail());
//        userAdvCollection.setSubtype(news.getSubtype());
//        int r = userAdvCollectionMapper.insert(userAdvCollection);
//        if(type == EnWzUser.USER_ADV_Collection.getIndex()){
//            news.setCollectionNumber(news.getCollectionNumber() + 1);
//            newsMapper.updateById(news);
//        }else if(type == EnWzUser.USER_ADV_Like.getIndex()){
//            news.setLikeNumber(news.getLikeNumber() + 1);
//            if(news.getLikeNumber()%10 == 0){
//                news.setReleaseTime(new Date());
//            }
//            newsMapper.updateById(news);
//        }
//        if(r > 0){
//            return Res.success();
//        }
//        return Res.fail();
//    }

    /**
     * 取消收藏、喜欢新闻
     */
//    public Res cancleNewsCollection(ParamMap p, Long userCode,int type) {
//        int c = userAdvCollectionMapper.delete(new EntityWrapper<WzUserAdvCollection>().eq("user_code",userCode).eq("adv_id",p.getStr("advId")).eq("type",type));
//        WzNews news = newsMapper.selectById(p.getStr("advId"));
//        if(news != null){
//            if(type == EnWzUser.USER_ADV_Collection.getIndex()){
//                if(news.getCollectionNumber() > 0){
//                    news.setCollectionNumber(news.getCollectionNumber() - 1);
//                    newsMapper.updateById(news);
//                }
//                return Res.success();
//            }else if(type == EnWzUser.USER_ADV_Like.getIndex()){
//                if(news.getLikeNumber() > 0){
//                    news.setLikeNumber(news.getLikeNumber() - 1);
//                    newsMapper.updateById(news);
//                }
//                return Res.success();
//            }
//        }else{
//            return Res.success();
//        }
//        return Res.fail();
//    }
//

    public boolean adCodeCheck(String adCode, String screenCity) {
        String[] screenCitys = StringUtils.split(screenCity,",");
        for(String s:screenCitys){
            if(s.equals(adCode)){
                return true;
            }
        }
        return false;
    }

    public String screenCity(String screenCity) {
        String[] screenCitys = StringUtils.split(screenCity,",");
        String adCode = "";
        for(String s:screenCitys){
            List<PfOpenCity> openCities = openCityMapper.selectList(new EntityWrapper<PfOpenCity>().eq("ad_code",s));
            if(openCities.size() > 0){
                adCode += openCities.get(0).getName() + " ";
            }
        }
        return adCode;
    }
}
